<template>
  <div class="loginContant" ref="loginContant">
    <div class="logo">
      <img src="../../assets/images/login-bg-small.jpg" alt="" srcset="" />
    </div>
    <div class="loginForm">
      <h3>机车乘务员非正常行车体感大数据分析系统</h3>
      <a-form
        id="components-form-demo-normal-login"
        :form="form"
        class="login-form"
        ref="form"
        @submit="handleSubmit"
      >
        <a-form-item>
          <a-input
            v-decorator="[
              'userName',
              { rules: [{ required: true, message: '用户名不正确!', min: 4 }] },
            ]"
            placeholder="用户名："
          >
            <a-icon
              slot="prefix"
              type="user"
              style="color: rgba(0, 0, 0, 0.25)"
            />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            v-decorator="[
              'password',
              {
                rules: [
                  { required: true, message: '密码不能低于6位!', min: 6 },
                ],
              },
            ]"
            type="password"
            placeholder="密码："
          >
            <a-icon
              slot="prefix"
              type="lock"
              style="color: rgba(0, 0, 0, 0.25)"
            />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-row class="code">
            <a-col :span="16">
              <a-input
                v-decorator="[
                  'code',
                  { rules: [{validator:checkCode,trigger: 'blur'}] },
                ]"
                placeholder="验证码："
              >
                <a-icon
                  slot="prefix"
                  type="property-safety"
                  style="color: rgba(0, 0, 0, 0.25)"
                />
              </a-input>
            </a-col>
            <!-- <img
              src="../../assets/images/login-yzm-img.jpg"
              alt=""
              srcset=""
              style="margin-left: 5px; height: 36px; font-size: 0"
            /> -->
            <createCode @refreshCode="refresh" @input="setCode" style="margin-left: 5px; height: 36px; font-size: 0" />
          </a-row>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" :loading="loading" @click="handleSubmit"
            >登录</a-button
          >
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import { login } from "@/api/login";
import throttle from "lodash.throttle"; //节流
import { mapMutations } from "vuex";
import { getTree } from "@/api/employee";
import createCode from "components/login/createCode";
export default {
  components: {
    createCode,
  },
  data() {
    return {
      codeNumber:'',
      loading: false,
      visible: false,
      confirmLoadingLoading: false,
      userName: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0,
          },
          sm: {
            span: 16,
            offset: 8,
          },
        },
      },
      btnText: "获取验证码",
      myInterval: null,
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
    this.findform = this.$form.createForm(this, { name: "findpassword" });
  },
  mounted() {
    if (localStorage.getItem("userName")) {
      this.form.setFieldsValue({ userName: localStorage.getItem("userName") });
      this.form.setFieldsValue({ password: localStorage.getItem("password") });
    }
  },
  methods: {
    //设置生成的验证码
    setCode(val){
      //this.$refs.form.validateField("code");
      this.codeNumber = val.toUpperCase()
    },
    refresh(){
      this.form.setFieldsValue({
        code: ''
      })
    },
    checkCode(rule, value, callback){//自定义校验
      if (value === '') {
         callback(new Error('请输入正确的验证码'))
      } else {
        if (value.toUpperCase()!== this.codeNumber) {
          callback(new Error('请输入正确的验证码'))
        }
        callback()
      }
    },
    //获取组织结构
    getOrganization() {
      getTree()
        .then((res) => {
          localStorage.setItem("organization", JSON.stringify(res.data.data));
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true;
          // var res = {
          //   code: 200,
          //   msg: "登录成功！",
          //   data: {
          //     token:
          //       "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb290SWQiOiI2YjE2MzI0MjQ4YTFkNGM4MDBhZWZhNjg3NjRkY2IwOSIsImxvZ2luTmFtZSI6ImNhb3p5IiwiaXNzIjoiaXNzdWVyIiwiY25hbWUiOiJtcmNhbyIsImRlZmF1bHRVbml0SWQiOiI2YjE2MzI0MjQ4YTFkNGM4MDBhZWZhNjg3NjRkY2IwOSIsImV4cCI6MTU5MzY2MDM3NywiaWF0IjoxNTkzNjUzMTc3LCJ1c2VySWQiOiJiYjEyNmRiYzU4Zjk4Y2RkOTBmMDUzYTY3YWEyNDY5YyJ9.Bdy95Eqc3aelvW5E2xzBjwV1pZRILw652ULSAKKe8_Q",
          //     refreshToken: "d2798ae52d4644229c9beefae56de833",
          //     userId: "bb126dbc58f98cdd90f053a67aa2469c",
          //     cname: "mrcao",
          //     unitId: "6b16324248a1d4c800aefa68764dcb09",
          //     rootId: "6b16324248a1d4c800aefa68764dcb09",
          //     unitName: "安徽省政府",
          //     isAdmin: 0,
          //     adminType: "10"
          //   }
          // };
          login({ account: values.userName, pwd: values.password })
            .then((res) => {
              if (res.data.code === 0) {
                this.$message.success("登录成功！");
                sessionStorage.setItem("defaultSelectedKeys", "");
                localStorage.setItem("userInfo", JSON.stringify(res.data.data));
                if (values.remember) {
                  localStorage.setItem("userName", values.userName);
                  localStorage.setItem("password", values.password);
                } else {
                  localStorage.removeItem("userName");
                  localStorage.removeItem("password");
                }
                this.getOrganization();
                this.$router.push("/console");
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              this.$message.destroy();
              this.$message.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.findform;
      if (value && value !== form.getFieldValue("password")) {
        callback("两次输入的密码不一致!");
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.findform;
      if (value && this.confirmDirty) {
        form.validateFields(["confirm"], { force: true });
      }
      callback();
    },
    compareToPhone(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    },
    showModal() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },
    ...mapMutations({
      setUserInfo: "SET_USERINFO",
    }),
  },
  destroyed() {
    if (this.myInterval) {
      clearInterval(this.myInterval);
    }
  },
};
</script>
<style lang="stylus" rel="stylesheet/stylus">
@import '~stylus/mixin.styl';

.loginContant {
  height: 100%;
  width: 100%;
  overflow: hidden;

  .logo {
    height: 100%;
    width: 100%;

    img {
      height: 100%;
      width: 100%;
      object-fit: cover;
    }
  }

  .loginForm {
    width:480px;
    height: 500px;
    position: absolute;
    padding: 10px;
    top: 18%;
    right: 5%;
    background: #fff;
    padding: 40px;

    h3 {
      height: 38px;
      line-height: 38px;
      font-size: 20px;
      font-weight: 700;
      margin-top: 10px;
      margin-bottom: 50px;
      color: #333;
      text-align: center;
    }

    .ant-input {
      height: 50px !important;
    }

    .code {
      display: flex;
      align-items: center;
    }

    .ant-btn {
      height: 50px;
      border: none;
      margin-top: 20px;
      width: 100%;
    }

    .login-form-forgot {
      float: right;
      color: #777;
    }
  }
}

.ant-drawer-content {
  .ant-input {
    height: 40px !important;
  }

  .ant-btn {
    height: 40px;
  }
}
</style>

<style></style>
